package com.tarena.charging.order.quartz;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.tarena.charging.order.feign.DeviceClient;
import com.tarena.charging.order.pojo.po.BillFailPO;
import com.tarena.charging.order.pojo.po.BillSuccessPO;
import com.tarena.charging.order.repository.BillRepository;
import com.tarena.charging.order.websocket.WebSocketServer;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

@Slf4j
public class DeviceCheckJob implements Job {
    public DeviceCheckJob(){}
    //充血模型 在构造方法中 当外部new当前对象的时候 就启动定时
    //同时可以使用构造方法的参数 接收业务数据
    public DeviceCheckJob(String billId,Integer gunId,Integer userId) throws SchedulerException {
        //调度器创建
        SchedulerFactory factory=new StdSchedulerFactory();
        Scheduler scheduler=factory.getScheduler();
        //封装当前 job对象
        JobDetail detail
            = JobBuilder.newJob(DeviceCheckJob.class)
            .withIdentity(
                "job_id_"+ UUID.randomUUID().toString(),"bill_device_group")
            .usingJobData("billId",billId)
            .usingJobData("gunId",gunId)
            .usingJobData("userId",userId)
            .build();
        //触发器
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        Date triggerTime=new Date(System.currentTimeMillis()+1000*60);
        triggerBuilder.startAt(triggerTime);
        scheduler.scheduleJob(detail,triggerBuilder.build());
        log.info("当前订单设备自检任务开始");
        scheduler.start();
    }


    @Override public void execute(JobExecutionContext context) throws JobExecutionException {
        //1. 拿到上下文 job 的参数
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        String billId= dataMap.getString("billId");
        Integer gunId=dataMap.getInt("gunId");
        Integer userId=dataMap.getInt("userId");
        //2 获取容器bean对象操作 查询成功 失败的订单信息 BillRepository
        BillRepository billRepository = SpringContextAwareUtils.getBean("billRepository", BillRepository.class);
        WebSocketServer webSocketServer = SpringContextAwareUtils.getBean("webSocketServer", WebSocketServer.class);
        //3.调用一个方法 查询是否存在数据 查询billId生成后 是否存在成功的bill记录
        //select * from charging_bill_success where bill_id=#{billId};
        BillSuccessPO billSuccessPO=billRepository.getSuccessBill(billId);
        //判断是否有订单成功
        if (billSuccessPO==null){
            //查询失败的信息 select * from charging_bill_fail where bill_id=#{billId}
            BillFailPO billFailPO=billRepository.getFailBill(billId);
            if (billFailPO==null){
                log.info("自检任务 1分钟已过 没有生成任何响应数据按照异常处理");
                //本次订单按照fail处理 新增到数据库一条数据
                billFailPO=new BillFailPO();
                billFailPO.setBillId(billId)
                    .setGunId(gunId)
                    .setFailDesc("自检任务 1分钟已过 没有生成任何响应数据")
                    .setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());
                billRepository.saveFail(billFailPO);
                //日志打印模拟
                log.info("调用后台保障服务,通知维修人员 尽快维修 billId:{},gunId:{}",billId,gunId);
                //实时通知用户 更换充电设备
                log.info("通知充电用户,请您更换设备");
                //调用优惠活动服务 给该用户发送优惠券码
                webSocketServer.pushMessage(userId,"充电枪 故障,请领取优惠券 http://localhost:9090/coupon");
                log.info("给当前充电用户 发送一张100元代金券");
            }else{
                log.info("设备自检失败 ,设备邮箱影充不了电 通知用户更换设备");
            }
        }else {
            //有成功信息
            log.info("设备自检成功,有响应,已经开始充电");
        }
    }
}
